const mysql = require('mysql')
const joi = require('joi')
const { DB_CONFIG } = require('../../config/index')

// 创建全局连接池（单例模式）
const pool = mysql.createPool(DB_CONFIG)

const dbMidWare = (req, res, next) => {
    // 从连接池获取连接（而不是每次创建新连接池）
    req.myDB = {
        query: (sql, params, callback) => {
            pool.getConnection((err, connection) => {
                if (err) return callback(err)
                connection.query(sql, params, (qErr, results) => {
                    connection.release() // 释放回连接池
                    callback(qErr, results)
                })
            })
        }
    }
    next()
}

const resBodyMidWare = (req, res, next) => {
    res.err = (message = '请求失败', data = null) => {
        res.send({
            data,
            message,
            status: 1
        })
    }
    res.success = (message = '请求成功', data = null) => {
        res.send({
            data,
            message,
            status: 0
        })
    }
    next()
}

const errMidWare = (err, req, res, next) => {
    if (err instanceof joi.ValidationError) return res.err(err.message)
    if (err.name == 'UnauthorizedError') return res.err('身份认证失败')

    res.err('未知错误')
    next()
}
module.exports = {
    // authMidWare,
    dbMidWare,
    resBodyMidWare,
    errMidWare
}